package com.gateway.demo.filter;

import com.gateway.demo.util.SpringUtil;
import com.gateway.demo.config.RtnMsg;
import com.gateway.demo.service.GateAuthService;
import com.linzf.common.util.JsonUtils;
import com.linzf.common.util.RtnConstant;
import com.netflix.client.ClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 类描述：自定义GlobalFilter，对所有的请求进行拦截
 *
 * @author linzf
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(AuthorizeFilter.class);

    /**
     * 请求头注解
     */
    private static final String AUTHORIZE_TOKEN = "x-access-token";
    /**
     * 鉴权的service
     */
    private static GateAuthService gAuthService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = request.getHeaders();
        // 地址鉴权返回的结果
        RtnMsg rtnMsg;
        // 需要鉴权的地址
        String authUrl = request.getURI().getPath();
        if(authUrl==null||authUrl.equals("")){
            rtnMsg = new RtnMsg(400,"非法访问！",null);
        }else{
            // 获取当前请求的token的值
            String token = headers.getFirst(AUTHORIZE_TOKEN);
            // 鉴权的键值对参数
            Map<String, String> auth = new HashMap<>(2);
            auth.put("authUrl", authUrl);
            auth.put("token", token);
            if (gAuthService == null) {
                gAuthService = SpringUtil.getBean(GateAuthService.class);
            }
            try{
                rtnMsg = gAuthService.authUrl(auth);
            }catch (RuntimeException e){
                logger.debug("错误原因：{}",e.getMessage());
                rtnMsg = new RtnMsg(RtnConstant.FAIL,"服务维护中",null);
            }
        }
        if (rtnMsg == null || rtnMsg.getCode() != RtnConstant.SUCCESS) {
            HttpHeaders httpHeaders = response.getHeaders();
            httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
            httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");
            DataBuffer bodyDataBuffer = response.bufferFactory().wrap(JsonUtils.objToJson(rtnMsg).getBytes());
            return response.writeWith(Mono.just(bodyDataBuffer));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
